package cn.bone.demo.mongo;

import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import org.bson.types.ObjectId;

import java.io.IOException;

/**
 * Created by superbone on 2016/10/13.
 *
 */
public class ObjectIdAdapter extends TypeAdapter<ObjectId>{
    @Override
    public void write(JsonWriter out, ObjectId value) throws IOException {
        out.value(value.toString());
       /*
        可以用如下的方式来自定义对象转json的格式
        out.beginObject();
        out.name("name").value(value.name);
        out.name("age").value(value.age);
        out.name("email").value(value.email);
        out.endObject();*/
    }

    @Override
    public ObjectId read(JsonReader in) throws IOException {

       /*
        使用如下法师来自定义json字符串转对象的规则
        User user = new User();
        in.beginObject();
        while (in.hasNext()) {
            switch (in.nextName()) {
                case "name":
                    user.name = in.nextString();
                    break;
                case "age":
                    user.age = in.nextInt();
                    break;
                case "email":
                case "email_address":
                case "emailAddress":
                    user.email = in.nextString();
                    break;
            }
        }
        in.endObject();
        return user;*/
        return null;
    }
}
